package br.com.ordersys.web.client.modules.utils;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;

public class XMLUtils {
	public static String getElementValue(Document doc, String name) {
		NodeList nl = doc.getElementsByTagName(name);

		if (nl.getLength() <= 0) {
			return null;
		}

		return nl.item(0).getFirstChild().getNodeValue();
	}

	public static Node getElement(Document doc, String name) {
		NodeList nl = doc.getElementsByTagName(name);

		if (nl.getLength() <= 0) {
			return null;
		}

		return nl.item(0);
	}
	
	public static Element createElement(Document doc, String name, String value){
		Element elem = doc.createElement(name);
		
		if(value != null && value.length() > 0){
			elem.appendChild(doc.createTextNode(value));
		}
		
		return elem;
	}
	
	public static Node getChildNode(Node baseNode, String name){
		NodeList nl = baseNode.getChildNodes();
		
		for(int i = 0; i < nl.getLength();i++){
			Node n = nl.item(i);
			if(n.getNodeName().equals(name)){
				return n; 
			}
		}
		
		return null;
	}
	
	public static String getChildNodeText(Node baseNode, String name){
		Node n = getChildNode(baseNode, name);
		
		if(n != null){
			Node text = n.getFirstChild();
			if(text != null){
				return text.getNodeValue();
			}
		}
		
		return null;
	}
	
	public static List<Node> getChildrenElements(Node baseNode, String name){
		NodeList nl = baseNode.getChildNodes();
		
		List<Node> result = new ArrayList<Node>();
		
		for(int i = 0; i < nl.getLength();i++){
			Node n = nl.item(i);
			
			if(n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)){
				result.add(n);
			}
		}
		
		return result;
	}

}
